﻿using Future.Common.Const;
using Future.Web.Extensions;
using Future.Web.Middlewares;
using Future.Web.Utility;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.FileProviders;

namespace Future.Web
{
    /// <summary>
    /// 运行配置
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// redis配置节点名称
        /// </summary>
        private const string REDISCACHEOPTIONS = "RedisCacheOptions";
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// service配置
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                //filter全局注册
                options.Filters.Add<CustomExceptionFilterAttribute>();
                options.Filters.Add<SucceededUnifyResultFilter>();
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateFormatString = DateTimeFormatConst.yyyy_MM_ddHHmmss;
            });

            services.AddHttpContextAccessor();
            services.AddSwaggerService();
            services.AddJwtService(_configuration);
            services.AddSqlsugarService(_configuration);
            //内存缓存
            services.AddDistributedMemoryCache();
            //Redis缓存
            //RedisCacheOptions redisCacheOptions = _configuration.GetSection(REDISCACHEOPTIONS).Get<RedisCacheOptions>();
            //redisCacheOptions.ConfigurationOptions.EndPoints.Add(redisCacheOptions.Configuration);
            //services.AddDistributedRedisCache(options =>
            //{
            //    options.ConfigurationOptions = redisCacheOptions.ConfigurationOptions;
            //});

            services.AddCors(options => options.AddPolicy("CorsPolicy",//解决跨域问题
                                builder =>
                                {
                                    builder.AllowAnyMethod()
                                   .SetIsOriginAllowed(_ => true)
                                   .AllowAnyHeader()
                                   .AllowCredentials();
                                }));
        }

        /// <summary>
        /// 请求管道配置 中间件配置
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseSwaggerAPI();
                app.UseCors("CorsPolicy");
            }
            GlobalContext.ServiceProvider = app.ApplicationServices;

            if (!env.IsDevelopment())
            {
                //非开发环境映射前端静态资源
                app.UseStaticFiles(new StaticFileOptions()
                {
                    ServeUnknownFileTypes = true,
                    FileProvider = new PhysicalFileProvider(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location) ?? string.Empty, "assets")),
                    RequestPath = new PathString("/assets")
                });
            }

            app.UseRouting();
            app.UseMiddleware<UnifyResultStatusCodesMiddleware>();
            app.UseAuthentication();
            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }
    }
}
